<?php
declare(strict_types=1);
namespace app\common\widget;
use aphp\core\Widget;
/**
 * 根据书籍ID或文档ID获取书籍目录树
 */
class BookDir extends Widget
{
    protected string $tag = 'doc';
    protected int $expire = 0;

    // 获取书籍目录树 $id 书籍ID $options['doc_id'] 文档ID
    public function set($id = '', array $options = []): array
    {
        if (isset($options['doc_id'])) {
            $id = db('doc')->where('id', $options['doc_id'])->value('book_id');
        }
        $get_type = $options['get_type'] ?? 0; // 0 目录树结构 1 获取表单选项
        // 获取表单选项
        if ($get_type == 1) {
            $list = db('doc')->where('book_id', $id)->where('pid=0')->order('sort ASC,id ASC')->column('title', 'id');
            return ['=根目录='] + $list;
        }
        // 获取目录树结构
        $list = db('doc')->field('id,book_id,title,sign,sub_count,pid,level,update_time,sort')->where('book_id', $id)->where('status=1')->order('sort ASC,id ASC')->select();
        if (empty($list)) {
            return [];
        }
        $now = time();
        return $this->_tree($list, 0, $now);
    }

    // 递归生成目录
    protected function _tree(array $data, int $pid, int $now = 0): array
    {
        $tree = [];
        foreach ($data as $v) {
            $v['is_new'] = ((($now - $v['update_time']) / 3600) < 24); // 小于24小时为新
            if ($v['pid'] == $pid) {
                $v['children'] = $this->_tree($data, $v['id'], $now);
                $tree[] = $v;
            }
        }
        return $tree;
    }
}